package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Xiao
 * @date 2021/10/22
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*System.out.println("请求方式:" + request.getMethod());
        System.out.println("访问URI:" + request.getRequestURI());*/
        //获取请求头
        String token = request.getHeader("Authorization");

        //已经在gateway中做了权限校验，此处无须再次校验token
        /*//判断Token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        //如果Token无效，返回状态码401并拦截
        if (!verifyToken) {
            response.setStatus(401);
            return false;
        }*/

        //如果Token有效，放行
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String mobile = (String) claims.get("mobile");
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);
        UserHolder.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
